﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Medianamik.Core;
using System.Web.UI;
using LiteralControl=System.Web.UI.LiteralControl;
using Medianamik.Core.Urls;
using Telerik.Web.UI;
using System.ComponentModel;
using System.Collections;


namespace Medianamik.UI.Controls
{

    //public class ReverseLookupURLCreator : BaseMedianamikControl, IMedianamikControl, INamingContainer
    //{
    //    #region Fields

    //    private const string URLBOX_PREFIX = "urlBox";

    //    private PlaceHolder phrURLs = new PlaceHolder();
    //    private Button btnAddURL = new Button();

    //    #endregion

    //    protected int ItemCount
    //    {
    //        get
    //        {
    //            return ViewState["ItemCount"] as int? ?? 0;
    //        }
    //        set
    //        {
    //            ViewState["ItemCount"] = value;
    //        }
    //    }

    //    #region Events

    //    #region Override

    //    protected override void CreateControlHierarchy(bool pUseDataSource)
    //    {
    //        if (Templates.Count <= 0)
    //        {
    //            throw new Exception(TypeName +" inherits from WebPage and therefore it must define at least one client template before a node of this type can be created.");
    //        }
            
    //        Controls.Add(new LiteralControl("<div style='border: solid 1px black; padding: 10px 10px 10px 10px'>"));

    //        btnAddURL.ID = "btnAdd";
    //        btnAddURL.Text = "Add";
    //        btnAddURL.Click += new EventHandler(btnAddURL_Click);
    //        btnAddURL.CausesValidation = false;
    //        Controls.Add(btnAddURL);
    //        Controls.Add(phrURLs);

    //        if (pUseDataSource)
    //        {
    //            var urls = DataSource as IEnumerable<NameValueNodePropertyCollection>;
               
    //            if (urls != null)
    //            { 
    //                foreach(var url in urls) 
    //                {
    //                    AddURL(phrURLs, url);
                       
    //                }

    //                ItemCount = urls.Count();
    //            }
                
    //        }
    //        else
    //        {
    //            for (int i = 0; i < ItemCount; i++)
    //            {
    //                AddURL(phrURLs);
    //            }
    //        }

    //        Controls.Add(new LiteralControl("<br/></div>"));
    //    }

       
    //    #endregion

    //    private void btnAddURL_Click(object sender, EventArgs e)
    //    {
    //        EnsureChildControls();
    //        AddURL(phrURLs);
    //        ItemCount++;
           
            
    //    }

    //    private void RemoveURL(object sender, EventArgs e)
    //    {
    //        EnsureChildControls();
    //        var urlBox = (Control)sender;
    //        urlBox.Visible = false;

    //    }

    //    #endregion

    //    #region Properties

    //    #region Override

    //    public override Type TypeOfValue
    //    {
    //        get { return typeof(IEnumerable<NameValueNodePropertyCollection>); }
    //    }

    //    public override object GetValue()
    //    {
    //        EnsureChildControls();
    //        var list = new List<NameValueNodePropertyCollection>();
    //        foreach(var box in phrURLs.Controls.OfType<URLBox>().Where(b=>b.Visible))
    //        {
    //            if(box.Value != null)
    //            {
    //                list.Add(box.Value);
    //            }
    //        }
    //        return list;
    //    }

    //    #endregion

        
    //    public List<String> Templates
    //    {
    //        get
    //        {
    //            return NodeTypeManager.GetNodeType(TypeName).ClientTemplatePaths;
                
    //        }
            
    //    }

    //    private List<WebSite> _webSites;
    //    public List<WebSite> WebSites
    //    {
    //        get
    //        {
    //            if (_webSites == null)
    //            {
    //                _webSites = ConfigManager.GetAllWebSites(MedianamikContext.Current.EditionCulture).ToList();
    //            }

    //            return _webSites;
    //        }
    //    }

       

    //    #endregion

    //    #region Methods
        

    //    private void AddURL(Control parent)
    //    {
    //        AddURL(parent, null);
    //    }

    //    private void AddURL(Control parent, NameValueNodePropertyCollection value)
    //    {
    //        URLBox urlBox = new URLBox();
    //        urlBox.RemoveURL += RemoveURL;
            
    //        parent.Controls.Add(urlBox);
    //        if (value != null)
    //        {
    //            urlBox.Value = value;
    //        }



    //    }

        

    //    #endregion

    //    #region Inner Classes

    //    private class URLBox : CompositeControl, INamingContainer
    //    {
    //        #region Fields

    //        TextBox txtURL = new TextBox();
    //        System.Web.UI.WebControls.DropDownList ddlTemplates = new System.Web.UI.WebControls.DropDownList();
    //        System.Web.UI.WebControls.DropDownList ddlWebSites = new System.Web.UI.WebControls.DropDownList();
    //        Button btnGenerateURL = new Button();
    //        Button btnRemoveURL = new Button();
    //        Button btnNewUrlLang = new Button();

    //        #endregion

    //        #region Events

    //        protected override void CreateChildControls()
    //        {
    //            if (ParentURLCreator.Templates.Count > 0 && ParentURLCreator.WebSites.Count > 0)
    //            {
    //                HtmlGenericControl br = new HtmlGenericControl("br");
    //                Controls.Add(br);

    //                Controls.Add(btnNewUrlLang);
    //                btnNewUrlLang.Text = "Create";
    //                btnNewUrlLang.CausesValidation = false;
    //                btnNewUrlLang.Click += new EventHandler(btnNewUrlLang_Click);

    //                txtURL.ID = "txtURL";
    //                Controls.Add(txtURL);

    //                if (ParentURLCreator.Templates.Count > 1)
    //                {
    //                    ddlTemplates.ID = "ddlTemplates";
    //                    Controls.Add(ddlTemplates);

    //                    ddlTemplates.Items.AddRange(ParentURLCreator.Templates.ConvertAll<ListItem>(t => new ListItem(t)).ToArray());
    //                    ddlTemplates.Items.Insert(0, "");
    //                }

    //                if (ParentURLCreator.WebSites.Count > 1)
    //                {
    //                    ddlWebSites.ID = "ddlWebSites";
    //                    Controls.Add(ddlWebSites);

    //                    ddlWebSites.Items.AddRange(ParentURLCreator.WebSites.ConvertAll<ListItem>(w => new ListItem(w.DisplayName, w.ID.ToString())).ToArray());
    //                    ddlWebSites.Items.Insert(0, "");
    //                }

    //                btnGenerateURL.ID = ID + "btnGenerateURL";
    //                btnGenerateURL.Click += new EventHandler(btnGenerateURL_Click);
    //                btnGenerateURL.Text = "GenerateURL";
    //                btnGenerateURL.CausesValidation = false;
    //                Controls.Add(btnGenerateURL);

    //                btnRemoveURL.ID = ID + "btnRemoveURL";
    //                btnRemoveURL.Click += new EventHandler(btnRemoveURL_Click);
    //                btnRemoveURL.Text = "RemoveURL";
    //                btnRemoveURL.CausesValidation = false;
    //                Controls.Add(btnRemoveURL);
                    
    //            }
    //        }

    //       private  void btnNewUrlLang_Click(object sender, EventArgs e)
    //        {
    //            var tempValue = this.Value;
    //            tempValue.CultureName = ParentURLCreator.EditionCultureName;
    //            tempValue.SetValue("path", string.Empty);
                
    //           Value = tempValue;
    //        }

    //        private void btnGenerateURL_Click(object sender, EventArgs e)
    //        {
    //            var node = NodeManager.GetNode<ContentNode>(ParentURLCreator.NodeId);
    //            //Contruire une Url
    //            var nodes = node.ParentsOfSameType.Where(n => n.UseInChildUrls).ToList();
    //            nodes.Sort((n1, n2) => n1.Depth.CompareTo(n2.Depth));
    //            nodes.Add(node);
    //            PathSegmentCollection segments = new PathSegmentCollection();
    //            int i = 0;
    //            nodes.ForEach(n => segments.Add(i++, new PathSegment(n.DisplayName)));
    //            IPathBuilder pathBuilder = new ObjectFactory<IPathBuilder>().Get();
    //            txtURL.Text = pathBuilder.BuildUrl(segments, CultureInfo.GetCultureInfo( ParentURLCreator.EditionCultureName ));

    //        }

    //        public event EventHandler RemoveURL;
    //        private void btnRemoveURL_Click(object sender, EventArgs e)
    //        {
    //            if (RemoveURL != null)
    //                RemoveURL(this, e);
    //        }

    //        #endregion

    //        #region Properties

    //        protected ReverseLookupURLCreator ParentURLCreator
    //        {
    //            get
    //            {
    //                return (ReverseLookupURLCreator)Parent.Parent;
    //            }
    //        }

    //        public Guid NodeId
    //        {
    //         get
    //         {
    //             return ViewState["NodeId"] as Guid?
    //                 ?? (Guid)(ViewState["NodeId"] = Guid.NewGuid() ) ;
    //         }
    //            set
    //            {
    //                ViewState["NodeId"] = value;
    //            }
    //        }

    //        public string CultureName
    //        {
    //            get
    //            {
    //                return ViewState["CultureName"] as string
    //                       ?? (string) (ViewState["CultureName"] = ParentURLCreator.EditionCultureName);
    //            }
    //            set
    //            {
    //                ViewState["CultureName"] = value;
    //            }
    //        }


    //        public NameValueNodePropertyCollection Value
    //        {
    //            get
    //            {
    //                EnsureChildControls();

    //                string template = "";
    //                string websiteId = "";

    //                if (ParentURLCreator.Templates.Count == 1 || ddlTemplates.SelectedValue == "")
    //                {
    //                    template = ParentURLCreator.Templates[0];
    //                }
    //                else
    //                {
    //                    template = ddlTemplates.SelectedValue;
    //                }

    //                if (ParentURLCreator.WebSites.Count == 1 || ddlWebSites.SelectedIndex < 1)
    //                {
    //                    websiteId = ParentURLCreator.WebSites[0].ID.ToString();
    //                }
    //                else
    //                {
    //                    websiteId = ddlWebSites.SelectedValue;
    //                }

    //                if (txtURL.Text.Length > 0 && template.Length > 0)
    //                {
    //                    var node = new NameValueNodePropertyCollection(NodeId, CultureName);
    //                    node.SetValue("template", template);
    //                    node.SetValue("path", txtURL.Text);
    //                    node.SetValue("website", websiteId);
    //                    node.SetValue("webpage", ParentURLCreator.NodeId);
                       
    //                    return node;
    //                }
                    
    //                return null;
    //            }
    //            set
    //            {
    //                EnsureChildControls();
    //                this.NodeId = value.NodeId;
    //                this.CultureName = value.CultureName;
                    
    //                var template = ddlTemplates.Items.FindByValue(value["template"]);
    //                if (template != null) {template.Selected = true; }
                    
    //                var website = ddlWebSites.Items.FindByValue(value["website"]);
    //                if (website != null) { website.Selected = true; }

    //                txtURL.Text = value["path"];

    //                bool sameCulture = (CultureName.EqualsIgnoreCase(ParentURLCreator.EditionCultureName ));
                    
    //                btnNewUrlLang.Visible = !sameCulture;
    //                SetControlEnabled(sameCulture);

    //            }
    //        }

            

    //        #endregion

    //        #region Methods

    //        public void SetControlEnabled(bool pEnabled)
    //        {
    //            txtURL.Enabled = pEnabled;
    //            ddlWebSites.Enabled = pEnabled;
    //            ddlTemplates.Enabled = pEnabled;
      
    //            btnRemoveURL.Enabled = pEnabled;
    //            btnGenerateURL.Enabled = pEnabled; 
    //        }
           

    //        #endregion
    //    }

    //    #endregion
    //}

    //#region OldCode
    ////public class ReverseLookupURLCreator : BaseMedianamikControl, IMedianamikControl, INamingContainer
    ////{
    ////    #region Fields

    ////    private RadGrid _grid = new RadGrid();

    ////    protected List<NameValueNodePropertyCollection> Nodes
    ////    {
    ////        get
    ////        {
    ////            return ViewState["Nodes"] as List<NameValueNodePropertyCollection>
    ////                ?? Enumerable.Empty<NameValueNodePropertyCollection>().ToList();
    ////        }
    ////        set
    ////        {
    ////            ViewState["Nodes"] = value;
    ////        }

    ////    }


    ////    #endregion

    ////    #region Events

    ////    #region Override

    ////    protected override void CreateControlHierarchy(bool pUseDataSource)
    ////    {
    ////        _grid.NeedDataSource += _grid_NeedDataSource;
    ////        _grid.Load += _grid_Load;
    ////        _grid.ItemDataBound += _grid_ItemDataBound;
    ////        _grid.InsertCommand += _grid_InsertCommand;


    ////        Controls.Add(_grid);

    ////        if (pUseDataSource)
    ////        {
    ////            SetupGrid(_grid);
    ////            _grid.DataSource = DataSource;
    ////            _grid.DataBind();

    ////            Nodes = (DataSource as IEnumerable<NameValueNodePropertyCollection>).ToList();
    ////        }

    ////    }

    ////    void _grid_Load(object sender, EventArgs e)
    ////    {
    ////        var webSiteColumn = _grid.Columns.FindByUniqueNameSafe("WebSiteColumn") as GridTemplateColumn;
    ////        webSiteColumn.ItemTemplate = new WebSiteItemTemplate(this.WebSites);
    ////        webSiteColumn.EditItemTemplate = new WebSiteEditTemplate(this.WebSites);
    ////    }

    ////    void _grid_InsertCommand(object source, GridCommandEventArgs e)
    ////    {
    ////        if (e.Item is GridEditableItem)
    ////        {
    ////            var item = (GridEditableItem)e.Item;
    ////            Hashtable values = new Hashtable();
    ////            item.ExtractValues(values);

    ////            var node = new NameValueNodePropertyCollection(Guid.NewGuid(), base.EditionCultureName, values);

    ////            Nodes.Add(node);
    ////            _grid.Rebind();
    ////        }

    ////    }

    ////    void _grid_ItemDataBound(object sender, GridItemEventArgs e)
    ////    {
    ////        if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    ////        {
    ////            var item = e.Item as GridEditableItem;
    ////            GridEditManager editMan = item.EditManager;

    ////        }
    ////    }

    ////    void _grid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
    ////    {
    ////        _grid.DataSource = Nodes;
    ////    }

    ////    private void SetupGrid(RadGrid pGrid)
    ////    {
    ////        pGrid.AutoGenerateColumns = false;
    ////        pGrid.AutoGenerateEditColumn = true;
    ////        pGrid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.Top;

    ////        var webSiteColumn = new GridTemplateColumn();
    ////        pGrid.Columns.Add(webSiteColumn);
    ////        webSiteColumn.UniqueName = "WebSiteColumn";

    ////    }



    ////    #endregion



    ////    #endregion

    ////    #region Properties

    ////    #region Override

    ////    public override Type TypeOfValue
    ////    {
    ////        get { return typeof(IEnumerable<NameValueNodePropertyCollection>); }
    ////    }

    ////    public override object GetValue()
    ////    {
    ////        EnsureChildControls();

    ////        return null;

    ////    }

    ////    #endregion

    ////    private List<WebSite> _webSites;
    ////    public List<WebSite> WebSites
    ////    {
    ////        get
    ////        {
    ////            if (_webSites == null)
    ////            {
    ////                _webSites = ConfigManager.GetAllWebSites(MedianamikContext.Current.EditionCulture).ToList();
    ////            }

    ////            return _webSites;
    ////        }
    ////    }


    ////    #endregion

    ////    #region Methods

    ////    #endregion


    ////}



    ////public class WebSiteEditTemplate : ITemplate, IBindableTemplate
    ////{

    ////    protected List<WebSite> WebSites { get; private set; }
    ////    #region ITemplate Members

    ////    public WebSiteEditTemplate(IEnumerable<WebSite> pWebSites)
    ////    {
    ////        WebSites = pWebSites.ToList();
    ////    }

    ////    public void InstantiateIn(Control container)
    ////    {
    ////        var ddl = new System.Web.UI.WebControls.DropDownList();
    ////        container.Controls.Add(ddl);
    ////        ddl.ID = "ddl";
    ////        ddl.DataSource = WebSites;
    ////        ddl.DataTextField = "DisplayName";
    ////        ddl.DataValueField = "ID";
    ////        ddl.DataBind();
    ////        var item = container.BindingContainer as GridItem;
    ////        var dataItem = item.DataItem as NameValueNodePropertyCollection;
    ////        if (dataItem != null)
    ////        {
    ////            var selectedItem = ddl.Items.Cast<ListItem>().FirstOrDefault(i => dataItem.NodeId.ToString().EqualsIgnoreCase(i.Value));
    ////            if (selectedItem != null) { selectedItem.Selected = true; }
    ////        }

    ////    }

    ////    #endregion

    ////    #region IBindableTemplate Members

    ////    public IOrderedDictionary ExtractValues(Control container)
    ////    {
    ////        var ddl = container.FindControl("ddl") as System.Web.UI.WebControls.DropDownList;
    ////        OrderedDictionary dico = new OrderedDictionary();
    ////        dico.Add("WebSite", ddl.SelectedValue);

    ////        return dico;
    ////    }

    ////    #endregion
    ////}

    ////public class WebSiteItemTemplate : ITemplate
    ////{
    ////    protected List<WebSite> WebSites { get; private set; }
    ////    public WebSiteItemTemplate(IEnumerable<WebSite> pWebSites)
    ////    {
    ////        WebSites = pWebSites.ToList();

    ////    }

    ////    #region ITemplate Members

    ////    public void InstantiateIn(Control container)
    ////    {
    ////        var ctrl = new LiteralControl();

    ////        container.Controls.Add(ctrl);
    ////        var item = container.BindingContainer as GridItem;
    ////        var dataItem = item.DataItem as NameValueNodePropertyCollection;
    ////        if (dataItem != null)
    ////        {
    ////            ctrl.Text = WebSites.Where(w => w.ID.ToString().EqualsIgnoreCase(dataItem["WebSite"]))
    ////                .Select(w => w.DisplayName).FirstOrDefault();
    ////        }


    ////    }




    ////    #endregion
    ////} 
    //#endregion


   

}
